package Mytest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;

public class Chat extends JFrame implements ActionListener {
    private JScrollBar  scrollBar;
    private JTextField inputMsg;
    private Socket socket;
    private DefaultListModel listMode1=new DefaultListModel<>();
    public static void main(String[] args) {

        Chat chat=new Chat();
        chat.init();
        chat.connServer();
    }

    public void connServer(){
        try {
             socket=new Socket("10.190.178.80",9999);
             //
            InputStream inputStream=socket.getInputStream();

            DataInputStream dataOutputStream =new DataInputStream(inputStream);
            String line=null;
            while ((line=dataOutputStream.readUTF())!=null){
                listMode1.addElement(line);
                //设置滚动条的位置
                scrollBar.setValue(scrollBar.getMaximum());
            }
            dataOutputStream.close();
            inputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取输入框的值
        String msg=inputMsg.getText().toString().trim();
        try {
            OutputStream outputStream=socket.getOutputStream();
            //将二进制转化为十进制
            DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
            //发送信息
            dataOutputStream.writeUTF(msg);
            //刷新
            dataOutputStream.flush();
            inputMsg.setText("");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void init(){
     //设置标题qq聊天
        listMode1.addElement("hello");
        listMode1.addElement("wolrd");
        JList jList=new JList(listMode1);
        JScrollPane scrollPane=new JScrollPane(jList);
        scrollBar=scrollPane.getVerticalScrollBar();
       this.add(scrollPane,BorderLayout.CENTER);

       JPanel panel=new JPanel(new BorderLayout());
        inputMsg=new JTextField();
       panel.add(inputMsg,BorderLayout.CENTER);
       JButton sendBtn=new JButton("发送");
       //按钮注册监听事情
        sendBtn.addActionListener(this);
        panel.add(sendBtn,BorderLayout.EAST);
        this.setSize(330,530);
        this.add(panel,BorderLayout.SOUTH);

        this.setVisible(true);

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.setLocationRelativeTo(null);

       JPanel cent=new JPanel(new GridLayout(2,1));

       //第一行第一列

    }

}
